const api = require('../../../../utils/utils')
Page({
  data: {
    iconUrl: api.iconUrl,
    // 用户表单数据
    user: {
      username: '14044440004', // 手机号
      sms_code: '234867', // 验证码
      password: "doctor0004", // 密码
      password2: "doctor0004", // 确认密码
    },
    send_status: true, // 控制发送验证码按钮 true表示可以获取
    remain_time: 60, // 间隔发送时间
    phone_number: '', // 提前获取手机号码
    // 表单校验规则
    usernameRules: [{
        required: true,
        message: '请输入手机号',
        trigger: 'blur'
      },
      {
        pattern: '^1[1-9][0-9]{9}$',
        message: '手机号不合法',
        trigger: 'blur'
      },
      {
        validator(rule, value, callback) {
          if(value==''||value==undefined||value==null){
            callback();
            return 
          }
          api.request('get', `/usernames/${value}/count/`, {}, false).then(res => {
            if (res.count === 1) {
              callback();
            } else {
              callback(false);
            }
          })
        },
        message: '手机号未修改',
        trigger: 'blur'
      }
    ],
    passwordRules: [{
        required: true,
        message: '请输入登录密码',
        trigger: 'blur'
      },
      {
        min: 8,
        max: 16,
        message: '密码长度在8-16个字符之间',
        trigger: 'blur'
      },
      {
        pattern: '^[A-Za-z0-9]+$',
        message: '密码必须由数字字母组成',
        trigger: 'blur'
      }
    ],
    password2Rules: [{
        required: true,
        message: '请确认密码',
        trigger: 'blur'
      },
      {
        validator(rule, value, callback, source) {
          const {
            password,
            password2
          } = source;
          if (password !== password2) {
            callback(false);
          }
          callback()
        },
        message: '两次密码输入不一致',
        trigger: 'change'
      }
    ],
    codeRules: [{
        required: true,
        message: '请输入验证码',
        trigger: 'blur'
      },
      {
        min: 6,
        max: 6,
        message: '验证码为6个数字组成',
        trigger: 'blur'
      },
      {
        pattern: '^[0-9]+$',
        message: '验证码必须由数字组成',
        trigger: 'blur'
      },
    ],
  },

  onLoad: function (options) {
    // 初始化表单信息
    wx.lin.initValidateForm(this)
    // 设置当前导航栏标题
    wx.setNavigationBarTitle({
      title: '找回密码'
    })
  },
  submit(event) {
    const toast = this.selectComponent("#mytoast")
    if (event.detail.isValidate === false) {
      toast.linShow({
        title: "输入格式错误！",
        icon: "error"
      })
      return
    }
    let source = event.detail.values
    let target = this.data.user
    Object.assign(target, source);
    api.request('put', '/passwords/phone/', target)
      .then(res => {
        toast.linShow({
          title: "修改成功",
          icon: "success"
        })
        // 修改成功返回
        setTimeout(() => {
          wx.navigateBack({
            delta: 1,
          })
        }, 1000)
      })
      .catch(err => {
        toast.linShow({
          title: "修改失败",
          icon: "error"
        })
      })
  },
  getPhoneNumber(event) {
    const {
      detail
    } = event
    this.setData({
      phone_number: detail.value
    })
  },
  // 请求发送短信验证码
  send_code() {
    const toast = this.selectComponent("#mytoast")
    // 判断手机号是否已经注册（账号是否存在）
    api.request('get', `/usernames/${this.data.phone_number}/count/`, {}, false)
      .then(res => {
        // 手机号已注册则发送短信
        if (res.count === 1) {
          api.request('get', `/sms_codes/${this.data.phone_number}/`, {}, false)
            .then(res => {
              this.setData({
                send_status: false
              })
              toast.linShow({
                title: "验证码发送成功",
                icon: "success"
              })
              // 验证码倒计时
              let time = setInterval(() => {
                let remain_time = this.data.remain_time;
                remain_time--;
                this.setData({
                  remain_time: remain_time
                });
                if (remain_time == 0) {
                  clearInterval(time);
                  this.setData({
                    remain_time: 60,
                    send_status: true
                  });
                }
              }, 1000)
            })
            .catch(err => {
              toast.linShow({
                title: "验证码发送失败，请检查手机号是否正确",
                icon: "error"
              })
            })
        } else {
          toast.linShow({
            title: "账号不存在",
            icon: 'error'
          })
        }
      })
  },
})